/**
 * Created by ying on 16-8-13.
 */
$(document).ready(function() {
    var data=get_local("data")
    get_sum_count()
    get_sum_money(data)
    get_save_money(data)
    generate_table(data)
    var time=get_time();
    show_time(time)
    jump_page()
})
function get_local(key){
    return JSON.parse(localStorage.getItem(key))
}
function get_sum_count(){
    var count=get_local("sum_count")||0;
    $("#sum_count").html(count);
}
function get_sum_money(data){
    var sum_money=0;
    _.each(data,function(key){
        sum_money+=key.price*(key.count-key.pro_count);
    })
    $("#sum_money").html(sum_money.toFixed(2));
}
function get_save_money(data){
    var save_money=0;
    _.each(data,function(key){
        save_money+=key.price*key.pro_count
    })
    $("#save").html(save_money.toFixed(2))
}
function generate_table(data,save) {
    $("#form").tmpl(data).appendTo("#product_list");
    var save=get_save(data)
    if(save.length!=0){
        $("#save_form").tmpl(save).appendTo("#save_table");
    } else{
        $(".caption,.save,#save_table").remove()
    }
}
function get_save(data){
    var save=[]
    _.each(data,function(key) {
        if(key.pro_count!=0){
            save.push({classification:key.classification, name:key.name,count:key.pro_count})
        }
    })
    return save
}
function get_time(){
    dateDigitToString = function (num) {
        return num < 10 ? '0' + num : num;
    };
    var currentDate = new Date(),
        year = dateDigitToString(currentDate.getFullYear()),
        month = dateDigitToString(currentDate.getMonth() + 1),
        date = dateDigitToString(currentDate.getDate()),
        hour = dateDigitToString(currentDate.getHours()),
        minute = dateDigitToString(currentDate.getMinutes()),
        second = dateDigitToString(currentDate.getSeconds()),
        formattedDateString = year + '年' + month + '月' + date + '日 ' + hour + ':' + minute + ':' + second;
    return formattedDateString;
}
function show_time(formattedDateString){
    $(".time").html(formattedDateString)
}
function jump_page() {
    $(".pay").click(function () {
    localStorage.clear()
        window.location.href = "../html/product_list.html"
    })
}